#include "RecognitionTester.h"

#include <stdio.h>
#include <iostream>
#include <vector>

#include "database/TrackBase.h"
#include "io/HMMBuilder.h"
#include "io/BaseSaver.h"
#include "common.h"


RecognitionTester::RecognitionTester(std::string baseDir) {
	// Build recognizer
	const std::string baseSuffix(".lrn");
	std::string fileName = baseDir;
	std::vector<std::string> files = vector<string>();
	getdir(baseDir, files);

	// number of states
	const unsigned n = 5;
	// size of alphabet
	const unsigned m = 8;
	// max number of training iterations
	const unsigned maxIter = 100;
	// training delta
	const double delta = 0.001;
	// number of models
	double eps = 1.0e-10;
	
	std::cout << "base directory: " << baseDir << "\n";
	
	for (unsigned int i = 0; i < files.size(); i++) {
		if (files[i].size() >= 5 && files[i].substr(files[i].size() - 3) == "lrn") {
		    	std::cout << "add " << files[i] << "\n";
		    	std::string symbol = files[i].substr(0, files[i].size() - 4);
		    	std::cout << "symbol = " << symbol << "\n";
		    	rec.addModel(symbol, HMM());
		    	rec[symbol].initLRB(n, m, 0.5);
		    	//rec[symbol].print();
		    	HMMBuilder::build((baseDir + files[i]).c_str(), rec[symbol]);
			//rec[symbol].print();
		}
	}
}

void RecognitionTester::isInterval(const LaserEvent& e) {
	printf("Listener notified about interval of time: %d.\n", e.time);
}
	
void RecognitionTester::isTrack(const LaserEvent& e) {
	if (rec.size() == 0) {
		printf("symbol base is empty!\n");
		return;
	}
	
	Track track = e.track;
	
	// size of alphabet
	const unsigned m = 8;
	
	// Recognize
	if (track.size() >= 10) {
		printf("track accepted.\n");
		Observation obs;
		track.convert(obs, m);
		std::string symbol = rec.recognize(obs);
		results.push_back(symbol);
		std::cout << "input recognized as " << symbol << "\n\n";
		expr += symbol;
		std::cout << "expression: " << expr << "\n\n";
	} else {
		printf("track rejected\n");
	}
}

const std::vector<std::string> RecognitionTester::getResults() const {
	return results;
}


